import config from '@/config/index.js'
import {
	getToken,
	setToken,
	genUrl
} from './fun.js'

function request(uri, method, data, query, is_login) {
	let header = {
		'X-Requested-With': 'XMLHttpRequest',
		'App-Source': config.app_source,
		'App-Version': config.app_version
	}
	if (is_login) {
		header['Authorization'] = getToken()
	}
	let url = genUrl(config.api_base_url + uri, query)

	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: method,
			header: header,
			data: data,
			timeout: config.api_timeout,
			success: response => {
				let res = response.data;
				let showMsg = false
				let msg = res.message
				if (data.returnAll == 1) {
					return resolve(res)
				}
				if (res.code == 200) {
					return resolve(res.data)
				} else if (res.code == 500 || res.code == 1002) {
					msg = res.message
					showMsg = true
				} else if (res.code == 401) { //token无效
					setToken('')
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}

				if (showMsg) {
					uni.showToast({
						title: msg,
						icon: 'none'
					})
				}
				return reject(new Error(res.message || 'Error'))
			},
			fail: error => {
				if (data.returnAll == 1) {
					return resolve(error)
				}
				uni.showToast({
					title: "网络异常",
					icon: 'none'
				})
				return reject(error)
			}
		})
	})
}

function get(url, query = {}, is_login = true) {
	return request(url, 'GET', {}, query, is_login)
}

function post(url, data = {}, query = {}, is_login = true) {
	return request(url, 'POST', data, query, is_login)
}

function put(url, data = {}, query = {}, is_login = true) {
	return request(url, 'PUT', data, query, is_login)
}

function del(url, data = {}, query = {}, is_login = true) {
	return request(url, 'DELETE', data, query, is_login)
}
export default {
	get,
	post,
	put,
	delete: del
}
